package com.alonsoruibal.chess.bitboard;

public class GenerateRookMagic {
	
	private static final long b_d = 0x00000000000000ffL; // down
	private static final long b_u = 0xff00000000000000L; // up
	private static final long b_r = 0x0101010101010101L; // right
	private static final long b_l = 0x8080808080808080L; // left
	
	
	private static long getRookShiftAttacks(long square, long all) {
		return Gen.checkSquareAttackedAux(square, all, +8, b_u) |
			Gen.checkSquareAttackedAux(square, all, -8, b_d) |
			Gen.checkSquareAttackedAux(square, all, -1, b_r) |
			Gen.checkSquareAttackedAux(square, all, +1, b_l);
	}
	
	static void generateAttacks() {
		
		RookMagic.rookMask = new long[64];
		RookMagic.rookMagic = new long[64][];
	
		long square = 1;
		byte i = 0;
		while (square != 0) {
			
			RookMagic.rookMask[i] = Gen.squareAttackedAuxSliderMask(square, +8, b_u)
					| Gen.squareAttackedAuxSliderMask(square, -8, b_d)
					| Gen.squareAttackedAuxSliderMask(square, -1, b_r)
					| Gen.squareAttackedAuxSliderMask(square, +1, b_l);

			// And now generate magics			
			int rookPositions = (1 << RookMagic.rookShiftBits[i]);
			RookMagic.rookMagic[i] = new long[rookPositions];
		    for (int j = 0; j < rookPositions; j++) {
		      long pieces = Gen.generatePieces(j, RookMagic.rookShiftBits[i], RookMagic.rookMask[i]);
		      int magicIndex = Gen.magicTransform(pieces, RookMagic.rookMagicNumber[i], RookMagic.rookShiftBits[i]);
		      RookMagic.rookMagic[i][magicIndex] = getRookShiftAttacks(square, pieces);
		    }
		
			square <<= 1;
			i++;
		}
		
	}
}
